package com.teamin.web.controller;

import com.teamin.config.ErrorCode;
import com.teamin.service.impl.wx.ParseXml;
import com.teamin.web.bind.CustomDateEditor;
import com.teamin.web.exception.GlobalErrorInfoException;
import com.teamin.web.model.ErrorInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.xml.sax.SAXException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BaseController {

	public static final String CIRCLE_SIGN_KEY="yT78k5jhRdGX3aTC" ; //签名的密钥
	public static final int CIRCLE_SIGN_TIME=604800 ; //分享的有效期,单位是秒 7天时间


	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor());
	}

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	public long getLoginUserId(HttpServletRequest request) throws GlobalErrorInfoException{
		Long userId = null;
		try {
			userId = Long.parseLong(request.getAttribute("loginUserId").toString()) ;
		} catch (Exception e) {
			logger.warn(e.getMessage());
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.FIND_USERID_FAIL));
		}
		return userId;
	}

	/**
	 * 直接返回数据
	 * @param response
	 * @param s
	 */
	public void flushDataByStringToResponse(HttpServletResponse response, String s) {

		OutputStream out = null;
		try {
			out = response.getOutputStream();
			out.write(s.getBytes("utf-8"));
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 解板请求数据
	 * @param request
	 * @param toClass
	 * @param <T>
	 * @return
	 */
	public <T> T getRequestData(HttpServletRequest request, Class<T> toClass) {
		T obj = null;
		try {
			obj = new ParseXml().parse(toClass, request.getInputStream());
		} catch (SAXException | IOException e) {
			e.printStackTrace();
		}
		return obj;
	}

	/**
	 * 从request 中读出流中的数据
	 * @param in
	 * @return
	 */
	public String getInputData(InputStream in) {
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String line = null;
		StringBuilder sb = new StringBuilder();
		try {
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
}
